package com.ruoyi.netty.client.initializer;

import com.ruoyi.netty.client.handler.NettyClientHandler;
import com.ruoyi.netty.server.pojo.NettyInit;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: [青衫] 'QSSSYH@QQ.com'
 * @Date: 2019-07-31 20:19
 * @Description: < 客户端初始化类 >
 */
@Component
public class NettyClientinitializer extends ChannelInitializer<SocketChannel>
	{

		@Autowired
		private NettyClientHandler nettyClientHandler;

		@Autowired
		private NettyInit nettyInit;

		@Override
		protected void initChannel(SocketChannel socketChannel) throws Exception
			{
				ChannelPipeline channelPipeline = socketChannel.pipeline();

				// 分隔符解码器
				ByteBuf delimiter = Unpooled.copiedBuffer(nettyInit.getSeparator().getBytes());
				channelPipeline.addLast(new DelimiterBasedFrameDecoder(nettyInit.getDeCodeSize(), delimiter));
				// 字符串解码 和 编码
				channelPipeline.addLast(new StringDecoder());
				channelPipeline.addLast(new StringEncoder());
/*
			channelPipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4));
			channelPipeline.addLast(new LengthFieldPrepender(4));
			channelPipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
			channelPipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));*/
				// 处理器
				channelPipeline.addLast(nettyClientHandler);
			}
	}
